﻿using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using SyCODE.Blog.Task;
using System.Web;
using System.IO;
using System.Xml;
using SyCODE.Component;

namespace SyCODE.Blog.Task
{
    /// <summary>
    /// 提供公开留言任务的实现
    /// </summary>
    [Serializable]
    public class LeaveTask : TaskBase
    {
        /// <summary>
        /// 公开留言任务的反序列化构造方法
        /// </summary>
        /// <param name="info">反序列化所需的数据</param>
        /// <param name="context">反序列化源的上下文</param>
        protected LeaveTask(SerializationInfo info, StreamingContext context)
        {
            Params = (NameValueCollection)info.GetValue("params", typeof(NameValueCollection));
        }

        /// <summary>
        /// 留言任务任务实现的构造函数
        /// </summary>
        /// <param name="_params">留言任务所需要的键值对数据</param>
        public LeaveTask(NameValueCollection _params)
        {
            Params = _params;
        }

        /// <summary>
        /// 留言任务的执行方法
        /// </summary>
        public override void Execute()
        {
            string leavePath = Path.Combine(AppPath.GetUserPhysicalPath(Params["bloger"]), "lastleave.xml");

            //更新最新留言的静态XML存档文件
            XmlDocument leaveDom = new XmlDocument();
            leaveDom.Load(leavePath);
            XmlElement leave = leaveDom.CreateElement("a");
            if (Params["source"].Trim().Length > 0)
            {
                leave.SetAttribute("id", Params["source"].Trim());
                leave.SetAttribute("href", "/" + Params["source"].Trim());
            }
            leave.SetAttribute("name", Params["sign"]);
            leave.AppendChild(leaveDom.CreateCDataSection(Function.StringCut(Params["content"], 64)));

            XmlNode body = leaveDom.DocumentElement.SelectSingleNode("body");
            body.AppendChild(leave);
            //如果存档里的留言数量超过10条则删除最早写入的一条留言
            if (body.ChildNodes.Count > 10)
            {
                body.RemoveChild(body.FirstChild);
            }
            leaveDom.Save(leavePath);
        }
    }
}